//
// Copyright (c) Microsoft Corporation.  All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
//
// (C) Copyright 2006 Marvell International Ltd.
// All Rights Reserved
//
/*++

THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
PARTICULAR PURPOSE.

Module Name: 

        usb20fn.h

Abstract:

        PXA USB Function Driver Header.

--*/
#ifndef __PXA_USB20FN_S_H_
#define __PXA_USB20FN_S_H_

#include <xllp_defs.h>
#include <xllp_dmac.h>
#include "xllp_gpio.h"
#include "xllp_mfp.h"
#include <xllp_u2d.h>
#include "xllp_clkmgr.h"
#include "xllp_i2c_proc.h"
#include "xllp_ost.h"
#include "..\csync_k.h"
#include <cmthread.h>
#include <CRegEdit.h>
#include <CRefCon.h>
#include <usbfn.h>


#ifndef SHIP_BUILD
#define STR_MODULE _T("monahans_usb20fn!")
#define SETFNAME() LPCTSTR pszFname = STR_MODULE _T(__FUNCTION__) _T(":")
#else
#define SETFNAME()
#endif

class USB20Device ;
class USB20Endpoint ;

#define USB20_DESCRIPTORS_MAX 32
#define USB20_DMA_BUFFER_SIZE 0x4000


// Endpoint Interrupt After shift.
#define EPINT_PACKET_COMPLETE   0x1
#define EPINT_FIFO_ERROR        0x2
#define EPINT_DMA_COMPLETE      0x4


#define USB20FUNCTION_DEFAULT_PRIORITY    100

#define USB20FUNCTION_PRIORITY_VALNAME    TEXT("Priority256")
#define USB20FUNCTION_PRIORITY_VALTYPE    REG_DWORD
// Debugging only registry.
#define USB20FUNCTION_EP0_STALL_COUNTER_VALNAME TEXT("EP0StallCounter")
#define USB20USBFUNCTION_EP0_STALL_COUNTER_VALTYPE REG_DWORD
#define USB20USBFUNCTION_BAD_SETUP_COUNTER_VALNAME TEXT("BadSetupCounter")
#define USB20USBFUNCTION_BAD_SETUP_COUNTER_VALTYPE REG_DWORD
	
#define USB20USBFUNCTION_DEFAULT_PRIORITY    100

#ifdef DEBUG 
#define ZONE_DATA DEBUGZONE(11)
#define ZONE_DMAOUT  DEBUGZONE(10)
#define ZONE_DMAIN  DEBUGZONE(9)
#endif

#define U2D_EP0_MAX_PACKET_SIZE 64

class CEndpointContainer : public CStaticContainer <USB20Endpoint, XLLP_U2D_USB_MAX_EP_NUM>
{
};

class USB20Device :public CEndpointContainer/* , public CRegistryEdit, public CMiniThread */
{
public:
   
    USB20Device(LPCTSTR lpActivePath);
    virtual ~USB20Device();

    virtual DWORD Init(PVOID pvMddContext,
        PUFN_MDD_INTERFACE_INFO pMddInterfaceInfo, PUFN_PDD_INTERFACE_INFO pPddInterfaceInfo);
//  PDD interface.
    virtual BOOL DeleteAllEndpoint();
// Endpoint Function.
    virtual DWORD IsEndpointSupportable (DWORD dwEndpoint,UFN_BUS_SPEED Speed,PUSB_ENDPOINT_DESCRIPTOR pEndpointDesc,
            BYTE bConfigurationValue=1, BYTE bInterfaceNumber=0, BYTE bAlternateSetting=0 );
    virtual DWORD InitEndpoint(DWORD dwEndpoint,UFN_BUS_SPEED Speed,PUSB_ENDPOINT_DESCRIPTOR pEndpointDesc,
            BYTE bConfigurationValue=1, BYTE bInterfaceNumber=0, BYTE bAlternateSetting=0 );
    virtual DWORD DeinitEndpoint(DWORD dwEndpoint );
    virtual DWORD StallEndpoint(DWORD dwEndpoint );
    virtual DWORD ClearEndpointStall( DWORD dwEndpoint );
    virtual DWORD ResetEndpoint(DWORD dwEndpoint );
    virtual DWORD IsEndpointHalted( DWORD dwEndpoint, PBOOL pfHalted );
    virtual DWORD IssueTransfer(DWORD  dwEndpoint,PSTransfer pTransfer );
    virtual DWORD AbortTransfer(DWORD dwEndpoint, PSTransfer pTransfer);
    
//  Endpoint Zero Special
    virtual DWORD SendControlStatusHandshake(DWORD dwEndpoint);
//  Device Function.
    virtual DWORD Start();
    virtual DWORD Stop();
    virtual BOOL IsCableAttached() { return TRUE; };
    virtual DWORD  SetAddress( BYTE  bAddress );

    virtual void PowerDown();
    virtual void PowerUp() ;
    
	virtual void  SetPowerState( CEDEVICE_POWER_STATE cpsNew ) ;
    virtual DWORD IOControl( IOCTL_SOURCE source, DWORD dwCode, PBYTE  pbInBuf, DWORD cbInBuf, PBYTE pbOutBuf, DWORD cbOutBuf,PDWORD  pcbActualOutBuf );

//  Register Access.
    
// Device Register Access.
        
    // Interrupt
    BOOL    EnableEndpointInterrupt(DWORD dwEndpointIndex,BOOL bEnable);
    DWORD   GetEndpointIntrStatus(DWORD dwEndpointIndex);

    // 
    void MddTransferComplete(PSTransfer pTransfer) {
        SETFNAME();
        if (m_pvMddContext && pTransfer) {
            //DEBUGMSG(ZONE_FUNCTION, (_T("%s MddTransferComplete pTransfer:0x%x"),pszFname,pTransfer));
            m_pfnNotify(m_pvMddContext, UFN_MSG_TRANSFER_COMPLETE, (DWORD) pTransfer);
        }
    }
    BOOL DeviceNotification( DWORD dwMsg, DWORD dwParam ) {
        SETFNAME();
        if (m_pvMddContext) {
            //DEBUGMSG(ZONE_FUNCTION, (_T("%s DeviceNotification dwMsg:0x%x,dwParam:0x%x"),pszFname,dwMsg,dwParam));
            return m_pfnNotify(m_pvMddContext, dwMsg, dwParam);
        }
        else {
            DebugBreak();
            return FALSE;
        }
    }

public:
    // Debugging function.
    void IncEp0StallCounter() {
#ifdef ERRORCOUNTERINREGISTRY
        DWORD dwEp0StallCounter = 0;
        if (!GetRegValue(USB20FUNCTION_EP0_STALL_COUNTER_VALNAME,(LPBYTE) &dwEp0StallCounter,sizeof(dwEp0StallCounter))) {
            dwEp0StallCounter = 0;
        }
        dwEp0StallCounter++;
        RegSetValueEx( USB20FUNCTION_EP0_STALL_COUNTER_VALNAME,USB20USBFUNCTION_EP0_STALL_COUNTER_VALTYPE,
            (PBYTE)&dwEp0StallCounter,sizeof(dwEp0StallCounter));
#endif
    }
    void IncBadSetupCounter() {
#ifdef ERRORCOUNTERINREGISTRY
        DWORD dwBadSetupCounter = 0;
        if (!GetRegValue(USB20USBFUNCTION_BAD_SETUP_COUNTER_VALNAME,(LPBYTE) &dwBadSetupCounter,sizeof(dwBadSetupCounter))) {
            dwBadSetupCounter = 0;
        }
        dwBadSetupCounter++;
        RegSetValueEx( USB20USBFUNCTION_BAD_SETUP_COUNTER_VALNAME, USB20USBFUNCTION_BAD_SETUP_COUNTER_VALTYPE,
            (PBYTE)&dwBadSetupCounter,sizeof(dwBadSetupCounter));
#endif
    }

public:
	inline P_XLLP_U2D_T GetXllpHandle(){return &m_XllpU2DHandle;}

	P_XLLP_U2D_REGISTERS_T  m_pRegsBase;          ///< Pointer to U2D.0's registers
 	P_XLLP_VUINT32_T	 	m_pMfpRegBase; 				///< Pointer to the MFP base registers
	P_XLLP_GPIO_T 			m_pGPIORegs;					///< Pointer to the GPIO base registers
	P_XLLP_OST_T 			m_pOSTRegs;					///< Pointer to the OST base registers	
	P_XLLP_I2C_T 			m_pI2CRegs;					///< Pointer to the I2C base registers	
protected: 
	

    virtual void PowerMgr(BOOL bOff);

	
    
    UFN_PDD_INFO m_PDDInfo;
        

	BOOL            m_fDoubleBuffer;

	BOOL    m_fIsCableAttached;
	BOOL 	m_fResumeOccurred;
	BOOL 	m_fForceResume;
	
	PVOID       m_pvMddContext;
	P_XLLP_CLKMGR_T m_pDCCLKReg;
	
    // Protected Fucntion
    BOOL        HardwareInit();
    BOOL        ReInit(); // For Cable Detach & Attach , We have to re-init the Device Controller.
    // Device Info.
    DWORD       m_dwCurConfigure;
    DWORD       m_dwCurInterface;

    PFN_UFN_MDD_NOTIFY      m_pfnNotify;

	DWORD		m_busSpeed;

public:
	DWORD ThreadRun();

private:
	XLLP_U2D_T m_XllpU2DHandle;
	BOOL InitMFPRM();
    

	HANDLE m_MfpRMDHandle;
	P_XLLP_MFP_RM_DB_ID_T m_pMfpRMDb;
};


class USB20Endpoint: public CRefObject,public CLockObject 
{
public :
    USB20Endpoint(USB20Device * const pUsbDevice, const DWORD dwPipeIndex,BOOL bDoubleBuffer = TRUE);
    virtual ~USB20Endpoint();
    virtual BOOL Init(PUSB_ENDPOINT_DESCRIPTOR pEndpointDesc,
            BYTE bConfigurationValue, BYTE bInterfaceNumber, BYTE bAlternateSetting);
    virtual BOOL ReInit();
    // Read & Write UDCCSR

	void ClearDMAStatus()
    {
	    XLLP_UINT32_T tmpDcsrClear = m_pU2DRegsBase->u2ddmacsr[m_dwEndpointIndex] & XLLP_DCSR_WRITABLES_MSK;
	    // Stop intr is not cleared by a simple write-back.  Must also
        //  restart the DMA (not done in ISR)
       	if (m_pU2DRegsBase->u2ddmacsr[m_dwEndpointIndex] & XLLP_DMAC_DCSR_STOP_INTR)
              tmpDcsrClear &= ~(XLLP_DMAC_DCSR_STOP_IRQ_EN);
                // Clear the status
      	m_pU2DRegsBase->u2ddmacsr[m_dwEndpointIndex]  = tmpDcsrClear;
		    	
    }

	void StopDMATransfer()
	{

		XLLP_UINT32_T temp=m_pU2DRegsBase->u2ddmacsr[m_dwEndpointIndex] ;
		temp &= XLLP_DCSR_WRITABLES_MSK; 
		temp &=~ XLLP_DMAC_DCSR_RUN;
		m_pU2DRegsBase->u2ddmacsr[m_dwEndpointIndex] = temp;
	}

		
    // Supported Function.
    virtual DWORD InitEndpoint(UFN_BUS_SPEED Speed,PUSB_ENDPOINT_DESCRIPTOR pEndpointDesc) 
    {
        // We should Reset Data Toggle Bit to DATA0. But we do know how.
        if( Init(pEndpointDesc,m_bConfigurationValue,m_bInterfaceNumber,m_bAlternateSetting) )
		 	return ERROR_SUCCESS;

		return ERROR_INVALID_DATA;
        
    }
    virtual DWORD DeinitEndpoint() 
	{
        return XllpU2DDisableInterrupt(	m_pUsbDevice->GetXllpHandle(), 
        								(XLLP_U2D_INTERRUPTS_T)m_dwEndpointIndex,
        								(XLLP_U2D_EP_INTERRUPT_TYPE_T)(U2D_SHORT_PACKET_COMPL_INT|U2D_PACKET_COMPL_INT)
        								);
    }
    virtual DWORD StallEndpoint();
    virtual DWORD ClearEndpointStall();
    virtual DWORD ResetEndpoint();
    virtual DWORD IsEndpointHalted(PBOOL pfHalted );
    virtual DWORD IssueTransfer(PSTransfer pTransfer ) ;
    virtual DWORD AbortTransfer(PSTransfer pTransfer );
    virtual DWORD SendControlStatusHandshake() { return ERROR_INVALID_PARAMETER; };
    // Attribute.
    USB_ENDPOINT_DESCRIPTOR GetEndpointDescriptor() { return m_epDesc; };
    // IST
    virtual DWORD   IST(DWORD dwIRBit, DWORD DMA=0) = 0 ;
    virtual void StartDMA(){};

#ifdef DEBUG
	void DumpDescript();
#endif

protected:

    USB20Device * const    m_pUsbDevice;
	volatile P_XLLP_U2D_REGISTERS_T  m_pU2DRegsBase;
	
    const XLLP_U2D_EP_T             m_dwEndpointIndex;
    USB_ENDPOINT_DESCRIPTOR m_epDesc;
    BYTE            m_bConfigurationValue,m_bInterfaceNumber,m_bAlternateSetting;
    volatile ULONG *        m_dataport;
    BOOL            m_fDoubleBuffer;
    PSTransfer      m_pCurTransfer;
    BOOL            m_fZeroPacket;
    BOOL            m_fStalled;
    
    // DMA support	
    volatile XLLP_UINT8_T *     m_vDMAData;				// DMA data buffer virtual pointer
	XLLP_UINT32_T		m_phyDMAData;			// DMA data buffer physical pointer

	DMA_ADAPTER_OBJECT m_DmaAdapter;		// DMA adaptor object, required by XLLP_DMAC module

    
    XLLP_DMAC_DESCRIPTOR_T * m_vDesc;		// DMA descriptor array, virtual address
    XLLP_UINT32_T		m_phyDesc;				// DMA descriptor array, physical address
    
    PHYSICAL_ADDRESS		m_PA;
    
    BOOL                m_bTerminated;     
    HANDLE              m_DMAEvent;
    
    int         m_Counter;
    int         m_LastTransfer;


//  Help Function.
    PSTransfer CompleteTransfer(DWORD dwError);
    void SendFakeFeature(BYTE bReuqest,WORD wFeatureSelector);
    DWORD XmitData(PBYTE pBuffer, DWORD dwLength);
    DWORD ReceiveData(PBYTE pBuffer, DWORD dwLength);    
};

#define EP0_MAX_PACKET_SIZE 0x10 
class USB20EndpointZero : public USB20Endpoint {
public:
    USB20EndpointZero(USB20Device * const pUsbDevice, BOOL bDoubleBuffer = TRUE ) 
        : USB20Endpoint(pUsbDevice, 0 ,bDoubleBuffer) 
    {
        m_bNeedAck = FALSE;
        m_bSetupDirIn = FALSE;
        m_fInIST = FALSE;
    }
    BOOL Init(PUSB_ENDPOINT_DESCRIPTOR pEndpointDesc,
            BYTE bConfigurationValue, BYTE bInterfaceNumber, BYTE bAlternateSetting);   
    virtual BOOL ReInit();
    DWORD ResetEndpoint();
    DWORD IssueTransfer(PSTransfer pTransfer );
    DWORD SendControlStatusHandshake() ;
    DWORD   IST(DWORD dwIRBit,DWORD DMA=0);
protected:
    BOOL  ContinueTransfer();
    BOOL  m_bNeedAck;
    BOOL  m_bSetupDirIn;
    BOOL  m_fInIST ;
private:
    USB_DEVICE_REQUEST m_backup_udr;
    USB_DEVICE_REQUEST m_cur_udr;
    BOOL               m_fBackedudr;
};

class USB20EndpointIn : public USB20Endpoint  
{
public:
    USB20EndpointIn(USB20Device * const pUsbDevice,DWORD dwEndpointIndex, BOOL bDoubleBuffer = TRUE);
		
	DWORD   IST(DWORD dwIRBit,DWORD) ;
private:
    void StartDMA();	
	
};


class USB20EndpointOut : public USB20Endpoint  
{

public:
    USB20EndpointOut(USB20Device * const pUsbDevice,DWORD dwEndpointIndex, BOOL bDoubleBuffer = TRUE );
	DWORD   IST(DWORD dwIRBit,DWORD DMA=0) ;

private:

    
    void StartDMA();	
	DWORD UpdateFromDMABuffer();
};


USB20Device * CreateUSB20Device(LPCTSTR lpActivePath);

#endif
